﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace ProjectSem3.Admin
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        private dataDataContext dc = new dataDataContext();
        Employee emp = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            emp= (Employee)Session["user"];

            if (!Page.IsPostBack)
            {
                if (emp != null)
                {
                    if (emp.RoleEmID == 1)
                    {
                        loaddata();
                    }
                    else
                    {
                        txtProduct.Enabled = false;
                        btnClick.Enabled = false;
                        btnClick.Visible = false;
                    }
                }
            }
        }

        protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
        {
            HiddenField hdf = ListView1.Items[e.NewSelectedIndex].FindControl("lblID") as HiddenField;

            Response.Redirect("ProductDetail.aspx?id="+hdf.Value);
        }

        //datapage listview
        protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
        {
            DataPager1.SetPageProperties(e.StartRowIndex, 5, false);
            loaddata();
        }

        protected void ListView1_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
        {

        }

        //insert stockdetail
        protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            HiddenField hdfProductID = ListView1.Items[e.ItemIndex].FindControl("lblID") as HiddenField;
            HtmlInputText txt = ListView1.Items[e.ItemIndex].FindControl("txtAmount") as HtmlInputText;

            if (Convert.ToInt32(txt.Value) > 0)
            {
                var mystockdetail = dc.StockDetails.Where(s => s.ProductID == Convert.ToInt32(hdfProductID.Value)).OrderByDescending(z => z.DateIn).Skip(0).Take(1).ToList();

                StockDetail std = null;
                if (mystockdetail.Count == 0)
                {
                    insertstockdetail(std, txt.Value, hdfProductID.Value);
                }
                else
                {
                    if (mystockdetail[0].DateIn.Value.ToShortDateString().Equals(DateTime.Now.ToShortDateString()))
                    {
                        std = dc.StockDetails.Single(m => m.StockDetailID == mystockdetail[0].StockDetailID);
                        std.Import = std.Import + Convert.ToInt32(txt.Value);
                        dc.SubmitChanges();
                    }
                    else
                    {
                        insertstockdetail(std, txt.Value, hdfProductID.Value);
                    }
                }
                loaddata();
            }
        }

        //Search product
        protected void btnClick_Click(object sender, EventArgs e)
        {
            if (txtProduct.Text.Trim().Length > 0)
            {
                int i = 1;
                var datasearch = getdata().Where(p => p.StockProduct.Name.ToLower().Contains(txtProduct.Text.ToLower())).ToList();
                datasearch.ForEach(x => x.idnumber = i++);
                ListView1.DataSource = datasearch;
                ListView1.DataBind();
            }
            else
                loaddata();
         
        }

        // insert stockdetail
        private void insertstockdetail(StockDetail std, string txt, string hdfProductID)
        {
            std = new StockDetail();
            std.DateIn = DateTime.Now;
            std.Import = (std.Import == null ? 0 : std.Import) + Convert.ToInt32(txt);
            std.ProductID = Convert.ToInt32(hdfProductID);
            std.StockID = getstock().StockID;
            dc.StockDetails.InsertOnSubmit(std);
            dc.SubmitChanges();
        }
        //if  new date insert new stock else update quantity
        private Stock getstock()
        {
            Stock st = null;
            
            try
            {
                st = dc.Stocks.Single(s => s.DateIn.Value.Date == DateTime.Now.Date && s.DateIn.Value.Month == DateTime.Now.Month && s.DateIn.Value.Year == DateTime.Now.Year);
            }
            catch (Exception)
            {
                //stock had increase in last time
                st = new Stock();
                st.DateIn = DateTime.Now;
                dc.Stocks.InsertOnSubmit(st);
                dc.SubmitChanges();
            }

            return st;
        }

        //load data
        private List<clsStockdetail> getdata()
        {
            int i = 1;
            //select stockdetail with sum numin
            var groupItem = from std in dc.StockDetails
                            group std by new { std.Product } into temp
                            select new { temp.Key.Product, datein = temp.Max(a => a.DateIn), quantity = temp.Sum(a => a.Import == null ? 0 : a.Import) - temp.Sum(a => a.Export == null ? 0 : a.Export) };
            //select all product
            var data = from p in dc.Products
                       from value in groupItem.Where(s => s.Product.ProductID == p.ProductID).DefaultIfEmpty()
                       select new clsStockdetail { StockProduct = p, Datein = value.datein == null ? "" : value.datein.ToString(), Quantity = value.quantity };

            List<clsStockdetail> daa = data.OrderByDescending(s => s.Datein).ToList();

            daa.ForEach(x => x.idnumber = i++);

            return daa;
        }
        private void loaddata()
        {
            ListView1.DataSource = getdata();
            ListView1.DataBind();
            foreach (ListViewItem item in ListView1.Items)
            {

                HiddenField hdf = (HiddenField)item.FindControl("hdfDateInsert");
                if (!hdf.Value.ToString().Equals(String.Empty))
                {
                    DateTime dt = Convert.ToDateTime(hdf.Value);

                    if (dt.ToShortDateString().Equals(DateTime.Now.ToShortDateString()))
                    {
                        HtmlTableRow tr = (HtmlTableRow)item.FindControl("trlist");
                        tr.Attributes.Add("style", "background-color: #99CCFF");
                    }
                }
            }

        }

        [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
        public static string[] GetCompletionList(string prefixText)
        {
            {
                return (from m in new dataDataContext().Products where m.Name.Contains(prefixText.ToLower()) select m.Name).ToArray();
            }

        }

    

     
    }
      
       
}